﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using BLL.Services;
using CartItem = FlowerShop.Core.Models.Tshoppingcars;



namespace 花店管理系统
{
    public partial class ShopCart : Form
    {
        public ShopCart()
        {
            InitializeComponent();
        }

        public static decimal profit = 0; // 利润
        private CartService cartService = new CartService();
        private List<Tshoppingcars> cartItems;
        private SqlDataAdapter daCartItem, daProduct;
        private DataSet ds = new DataSet();

        void init()
        {
            DB.GetCn();
            string str = "select C_id,t_id,G_id,G_name,jiage,kuchun from Tshoppingcars where t_id=" + Convert.ToInt32(Login.t_id) + "";
            daCartItem = new SqlDataAdapter(str, DB.cn);
            daCartItem.Fill(ds, "CartItem_info");
            string sdr = "select * from Tgood";
            daProduct = new SqlDataAdapter(sdr, DB.cn);
            daProduct.Fill(ds, "product_info");
            DB.cn.Close();
        }

        void showXz() // 选择列
        {
            DataGridViewCheckBoxColumn acCode = new DataGridViewCheckBoxColumn();
            acCode.Name = "acCode";
            acCode.HeaderText = "选择";
            dgvCart.Columns.Add(acCode);
        }

        private void ShopCart_Load(object sender, EventArgs e)
        {
            DB.GetCn();
            cartService.AddToCart(Convert.ToInt32(Login.t_id), Convert.ToInt32(Form1.Productid), 1);
            Bind();
            DB.cn.Close();
        }

        void dgvHead()
        {
            dgvCart.Columns[0].HeaderText = "购物车编号";
            dgvCart.Columns[1].HeaderText = "用户编号";
            dgvCart.Columns[2].HeaderText = "商品编号";
            dgvCart.Columns[3].HeaderText = "商品名称";
            dgvCart.Columns[4].HeaderText = "价格";
            dgvCart.Columns[5].HeaderText = "购买数量";
        }

        private void dgvCart_CellContentClick(object sender, DataGridViewCellEventArgs e) // 多选转为单选
        {
            if (dgvCart.Rows.Count > 0)
            {
                for (int i = 0; i < dgvCart.Rows.Count; i++)
                {
                    DataGridViewCheckBoxCell ck = dgvCart.Rows[i].Cells["acCode"] as DataGridViewCheckBoxCell;
                    if (i != e.RowIndex)
                    {
                        ck.Value = false;
                    }
                    else
                    {
                        ck.Value = true;
                    }
                }
            }
        }

        private void btnRemoveSelected_Click(object sender, EventArgs e)
        {
            for (int i = dgvCart.Rows.Count - 1; i >= 0; i--)
            {
                if (dgvCart.Rows[i].Cells["acCode"].Value != null && (bool)dgvCart.Rows[i].Cells["acCode"].Value)
                {
                    Tshoppingcars itemToRemove = (Tshoppingcars)dgvCart.Rows[i].DataBoundItem;
                    int productId = itemToRemove.G_id;
                    cartService.RemoveFromCart(Convert.ToInt32(Login.t_id), productId);

                    // 从数据源中删除项
                    cartItems.Remove(itemToRemove);
                }
            }

            // 重新绑定数据源
            Bind();
        }

        void UpdateDB()
        {
            try
            {
                SqlCommandBuilder dbCartItem = new SqlCommandBuilder(daCartItem);
                daCartItem.Update(ds, "CartItem_info");
                SqlCommandBuilder dbProduct = new SqlCommandBuilder(daProduct);
                daProduct.Update(ds, "product_info");
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnReset_Click(object sender, EventArgs e) // 重新计算总价
        {
            var totals = cartService.CalculateCartTotals(Convert.ToInt32(Login.t_id));
            lblTotalPrice.Text = totals.totalPrice.ToString();
            profit = totals.totalProfit;
        }

        void Bind()
        {
            InitializeDataSource();
            (decimal totalPrice, decimal totalProfit) totals = CalculateTotals();
            lblTotalPrice.Text = totals.totalPrice.ToString();
            profit = totals.totalProfit;
            List<CartItem> cartItems = cartService.GetCartItems(Convert.ToInt32(Login.t_id));
            dgvCart.DataSource = cartItems;
            dgvHead();
            showXz();
        }

        private (decimal totalPrice, decimal totalProfit) CalculateTotals()
        {
            return cartService.CalculateCartTotals(Convert.ToInt32(Login.t_id));
        }

        private void InitializeDataSource()
        {
            init();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            cartService.ClearCart(Convert.ToInt32(Login.t_id));
            Bind();
        }

        private void btnCance_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (dgvCart.Rows.Count == 0)
            {
                MessageBox.Show("请先添加购物车");
                return;
            }

            List<string> selectedFlowerNames = GetSelectedItems();
            ProcessCheckout(selectedFlowerNames);
        }

        private void ProcessCheckout(List<string> selectedFlowerNames)
        {
            cartService.ClearCart(Convert.ToInt32(Login.t_id));
            SubmitCart sl = new SubmitCart(selectedFlowerNames);
            sl.ShowDialog();
            this.Close();
        }

        private List<string> GetSelectedItems()
        {
            List<string> selectedFlowerNames = new List<string>();
            foreach (DataGridViewRow row in dgvCart.Rows)
            {
                if (row.Cells["acCode"].Value != null && (bool)row.Cells["acCode"].Value)
                {
                    selectedFlowerNames.Add(row.Cells["G_name"].Value.ToString());
                }
            }

            return selectedFlowerNames;
        }
    }
}
